package com.liuzhou.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.liuzhou.util.C3P0Util;



public class MyFilter implements Filter{
	/**不需要过滤的请求*/
	private List<String> list;
	
	
	//服务容器销毁的时候运行的方法
	@Override
	public void destroy() {
	}
	
	//过滤器的处理逻辑方法
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		//统一设置编码
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		
		//获取用户的URI
		String uri = req.getRequestURI();
		//不需要过滤的请求
		String reqPath = uri.substring( uri.lastIndexOf("/") + 1 );
		
		System.out.println("正在过滤reqPath:"+ reqPath);
		
		if( list.contains(reqPath) ){
			chain.doFilter(req, resp);
			return;
		}
		
		
		//登录验证
		HttpSession session = req.getSession();
		Object userObj = session.getAttribute("loginUser");//setAttribute 写在 LoginAction.java 中
		if( userObj == null ){//访问不合法
			resp.sendRedirect("loginPage.action");
			return;
		}
		
		
		//过滤器放过请求
		chain.doFilter(req, resp);
	}

	//服务器启动的时候初始化方法
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		C3P0Util.close( C3P0Util.getConnection() );
		
		list = new ArrayList<String>();		
		list.add("loginPage.action");
		list.add("login.action");
		list.add("checkUserName.action");
		list.add("getAuthCode.action");
	}

}
